import axios from 'axios';
import { Message } from 'element-ui'

const service = axios.create({
  baseURL: process.env.VUE_APP_TDT_API,
  timeout: 30000
})

const errorCodeMap = new Map()
errorCodeMap.set(501, '服务器不支持')
errorCodeMap.set(502, '无法访问后台服务')
errorCodeMap.set(503, '无可用服务实例')
errorCodeMap.set(504, '后台服务不可用')

function fetchResponseErrorMessage (res) {
  let errorMessage = res.message || '未知的服务端错误'
  if (res.code === 500) {
    errorMessage = res.message || '未知的服务端错误'
  } else if (res.code === 501) {
    errorMessage = res.message || '请求的服务未实现'
  } else if (res.code === 502) {
    errorMessage = res.message || '无法访问服务实例'
  } else if (res.code === 503) {
    errorMessage = res.message || '无可用的服务实例'
  } else if (res.code === 403) {
    errorMessage = '用户无权访问权限'
  } else if (res.code === 404) {
    errorMessage = '数据或服务不存在'
  }
  return errorMessage
}

service.interceptors.request.use(
  config => {
    return config
  },
  error => {
    console.log('error', error)
    return Promise.reject(error)
  }
)

service.interceptors.response.use(
  response => {
    return new Promise((resolve, reject) => {
      const res = response.data
      if (response.config && response.config.responseType === 'blob') {
        resolve(res)
        return
      }

      if (response.config && response.config.returnRawData) {
        resolve(res)
        return
      }
      // 搜索返回码 1000, 3001
      // 地理编码返回码 '0', '101'
      // 行政区划返回码 '100', '101'
      if (res.status && res.status.infocode && (res.status.infocode === 1000 || res.status.infocode === 3001)) {
        resolve(res)
      } else if (res.status && (res.status === '0' || res.status === '101')) {
        resolve(res)
      } else if (res.returncode && (res.returncode === '100' || res.returncode === '101')) {
        resolve(res)
      } else {
        let errorMessage = fetchResponseErrorMessage(res)
        if (!response.config || response.config.showErrorMessage !== false) {
          Message({
            message: errorMessage,
            type: 'error',
            duration: 2 * 1000
          })
        }
        reject(errorMessage)
      }
    })
  },
  error => {
    return new Promise((resolve, reject) => {
      const response = error.response || {}
      let res = response.data
      if (!res || typeof (res) === 'string' || (response.config && response.config.responseType === 'blob')) {
        if (response.config && response.config.responseType === 'blob') {
          var reader = new FileReader()
          reader.addEventListener('loadend', function (e) {
            try {
              res = JSON.parse(e.target.result)
            } catch (error) {
              res = {
                code: response.status,
                message: errorCodeMap.get(response.status) || response.statusText
              }
            }

            if (response.config && response.config.returnRawData) {
              resolve(res)
              return
            }

            let errorMessage = fetchResponseErrorMessage(res)
            if (!response.config || response.config.showErrorMessage !== false) {
              Message({
                message: errorMessage,
                type: 'error',
                duration: 2 * 1000
              })
            }
            reject(errorMessage)
          })
          reader.readAsText(response.data)
          return
        } else {
          res = {
            code: response.status,
            message: errorCodeMap.get(response.status) || response.statusText
          }
        }
      }

      if (response.config && response.config.returnRawData) {
        resolve(res)
        return
      }

      let errorMessage = fetchResponseErrorMessage(res)
      // 针对令牌失效情况，重新登录
      if (!response.config || response.config.showErrorMessage !== false) {
        Message({
          message: errorMessage,
          type: 'error',
          duration: 2 * 1000
        })
      }
      reject(errorMessage)
    })
  }
)

export default service
